<?php

/**
 * 字符串截取，支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false === $slice) {
            $slice = '';
        }
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice.'...' : $slice;
}
/***
 * 时间函数
 */
 function toDate ($time="",$p="Y-m-d H:i:s"){
 
    if($time==""){
       $time =time();
    }
     return date($p,$time);
 }

/**
 * 判断文件路径是否存在，不存在则创建文件
 */
 function mkfile($path){
 
 	$arr = explode("/",$path);
 	$count = count($arr);
 	$dir = "";
 	for($i=0;$i<$count;$i++){
 		if($arr[$i]=="") continue;
 		$dir.="/".$arr[$i];
 		if(!file_exists($dir)){ mkdir($dir,"0777");}
 	
 	}
 }
 /**
 * 字符串转换为数组，主要用于把分隔符调整到第二个参数
 * @param  string $str  要分割的字符串
 * @param  string $glue 分割符
 * @return array
 *
 */
function str2arr($str, $glue = ','){
    return explode($glue, $str);
}
 /**
 * 数组转换为字符串，主要用于把分隔符调整到第二个参数
 * @param  array  $arr  要连接的数组
 * @param  string $glue 分割符
 * @return string
 *
 */
 function arr2str($arr, $glue = ','){
    return implode($glue, $arr);
 }
 /**
 * @abstract 根据年份和月份获取最大日（28、29、30或31）
 * @param integer $year
 * @param integer $month
 * @return integer 返回最大日
 */
function get_max_day($year, $month)
{
	if ($month == 1 || $month == 3 || $month == 5 || $month == 7 || $month == 8 || $month == 10 || $month == 12)
	{
		return 31;
	}
	elseif ($month == 2)
	{
		if ($year % 400 == 0 || ($year % 4 == 0 && $year % 100 != 0)) // 闰年
		{
			return 29;
		}
		else
		{
			return 28;
		}
	}
	else
	{
		return 30;
	}
}
/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key  加密密钥
 * @param int $expire  过期时间 单位 秒
 * @return string
 * 
 */
function clx_encrypt($data, $key = '', $expire = 0) {
    $key  = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    $str = sprintf('%010d', $expire ? $expire + time():0);

    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
    }
    return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
}

/**
 * 系统解密方法
 * @param  string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param  string $key  加密密钥
 * @return string
 * 
 */
function clx_decrypt($data, $key = ''){
    $key    = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data   = str_replace(array('-','_'),array('+','/'),$data);
    $mod4   = strlen($data) % 4;
    if ($mod4) {
       $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data,0,10);
    $data   = substr($data,10);

    if($expire > 0 && $expire < time()) {
        return '';
    }
    $x      = 0;
    $len    = strlen($data);
    $l      = strlen($key);
    $char   = $str = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }else{
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}
/**
* 对查询结果集进行排序
* @access public
* @param array $list 查询结果
* @param string $field 排序的字段名
* @param array $sortby 排序类型
* asc正向排序 desc逆向排序 nat自然排序
* @return array
*/
function list_sort_by($list,$field, $sortby='asc') {
   if(is_array($list)){
       $refer = $resultSet = array();
       foreach ($list as $i => $data)
           $refer[$i] = &$data[$field];
       switch ($sortby) {
           case 'asc': // 正向排序
                asort($refer);
                break;
           case 'desc':// 逆向排序
                arsort($refer);
                break;
           case 'nat': // 自然排序
                natcasesort($refer);
                break;
       }
       foreach ( $refer as $key=> $val)
           $resultSet[] = &$list[$key];
       return $resultSet;
   }
   return false;
}
/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 * 
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree  原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array  $list  过渡用的中间数组，
 * @return array        返回排过序的列表数组
 * 
 */
function tree_to_list($tree, $child = '_child', $order='id', &$list = array(),$level = 0){

    if(is_array($tree)) {
        $refer = array();
        foreach ($tree as $key => $value) {
            $reffer = $value;          
            $reffer['level'] = $level;
            $reffer['html'] = str_repeat('&nbsp;&nbsp;',$level).'├'; 
            if(isset($reffer[$child])){ $reffer['havesun'] = 1;}
            $list[] = $reffer;
            if(isset($reffer[$child])){
                unset($reffer[$child]);
                tree_to_list($value[$child], $child, $order, $list,$level+1);
            }           
        }
    }
    return $list;
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * 
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

function redirect_url($url=""){
	if($url){
	   cookie('redirect_url', $url);
	}else{
		
	  $url = cookie('redirect_url');
  	  return empty($url) ? __APP__ : $url;
	
	}
}
//数组转化为json;
function encode_json($str) {
		return json_encode(url_encode($str));
}
//json转化为数组;
function decode_json($str) {
	return url_decode(json_decode($str,true));
}
/**
 *
*/
function url_encode($str) {
		if(is_array($str)) {
			foreach($str as $key=>$value) {
				$str[urlencode($key)] = url_encode($value);
			}
		} else {
			$str = urlencode($str);
		}
	
		return $str;
 }
  
 function url_decode($str) {
 	if(is_array($str)) {
 		foreach($str as $key=>$value) {
 			$str[urldecode($key)] = url_decode($value);
 		}
 		
 	} else {
 		
 		$str = urldecode($str);
 	}
 
 	return $str;
 }
     /**
     * 发送HTTP请求方法
     * @param  string $url    请求URL
     * @param  array  $params 请求参数
     * @param  string $method 请求方法GET/POST
     * @return array  $data   响应数据
     */
    function http($url, $params, $method = 'GET', $header = array(), $multi = false){
        $opts = array(
                CURLOPT_TIMEOUT        => 30,
                CURLOPT_RETURNTRANSFER => 1,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_HTTPHEADER     => $header
        );
        /* 根据请求类型设置特定参数 */
        switch(strtoupper($method)){
            case 'GET':
               if(strpos($url,'?')){
					 $opts[CURLOPT_URL] = $url . http_build_query($params);
				}else{
					 $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
				}
                break;
            case 'POST':
                //判断是否传输文件
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                throw new Exception('不支持的请求方式！');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if($error) throw new Exception('请求发生错误：' . $error);
        return  $data;
    }
/**输出中文的星期
 * date('w')
 * @param $j
 * author:clx
 */
function weekDay($j)
{
    if ($j==1)
        return  "星期一";
    if ($j==2)
        return "星期二";
    if ($j==3)
       return "星期三";
    if ($j==4)
       return "星期四";
    if ($j==5)
        return "星期五";
    if ($j==6)
        return "星期六";
    if ($j==0)
        return  "星期天";
}
/*
*根据ip获取地区信息
*/
function  getProvinceByIp($ip){
		$url = 'http://apis.baidu.com/apistore/iplookupservice/iplookup';
		$param['ip'] = $ip;
		$header = array(
			'apikey: a27224b481049423dadb043a36783077'
		);
		$rst = json_decode(http($url,$param,'GET',$header),true);
		return $rst;
}

/*
*给图片添加文字信息
*$oldFile=原始文件 $newFile =新的文件 为空 就不保存 $text= 文字信息 $x,$y开始的位置坐标 $angle 弧度 
*$size =文字大小 $colorX,$colorY,$colorZ字体颜色 $font='字体'
*
*/
function addImgWord($oldFile,$newFile=null,$text,$x,$y,$angle,$size=70,$colorX='255',$colorY='0',$colorZ='0',$font='./STKAITI.TTF'){
	
	//创建图片的实例
	$dst = imagecreatefromstring(file_get_contents($oldFile));
	$textColor = imagecolorallocate($dst,$colorX,$colorY,$colorZ);//字体颜色
	imagefttext($dst, $size, $angle, $x, $y, $textColor, $font, iconv("gb2312","UTF-8",$text));
	//输出图片
	list($dst_w, $dst_h, $dst_type) = getimagesize($oldFile);
	switch ($dst_type) {
		case 1://GIF
			//header('Content-Type: image/gif');
			$rst = imagegif($dst,$newFile);
			break;
		case 2://JPG
			//header('Content-Type: image/jpeg');
			$rst = imagejpeg($dst,$newFile);
			break;
		case 3://PNG
			//header('Content-Type: image/png');
			$rst = imagepng($dst,$newFile);
			break;
		default:
			break;
	}
	imagedestroy($dst);
	return $rst;
}
/**
$dst_path = 'test.jpg';
$imgInfo = getimagesize($dst_path);
$rst = addImgWord($dst_path,'./b.jpg','快乐编程快乐编程快乐编程',0,$imgInfo[1]/2,10);
**/

 function sendMsg($accout,$content){

    $apiUrl = 'http://web.1xinxi.cn/asmx/smsservice.aspx';
    $data['name'] = '15907185954';
    $data['pwd'] = '6931F1D65E5BD9A962D98F569B5C';
    $data['content'] = $content;
    $data['mobile'] = $accout ;
    $data['stime'] = date('Y-m-d H:i:s');
    $data['sign'] = 'testsign';
    $data['type'] = 'pt';
    return http($apiUrl,$data,'post');

}


/********************************Email**********************************/
//下面定义一个发送邮件的函数,已经测试通过。
//$sendto_email：邮件发送地址
//$subject：邮件主题
//$body:邮件正文内容
//$sendto_name邮件接受方的姓名，发送方起的名字。一般可省。
function smtp_mail($to_email, $subject = null, $body = null, $to_name = null) {
//    vendor("PHPMailer.class",'','phpmailer.php');
    vendor("PHPMailer.class#phpmailer");
    //新建一个邮件发送类对象
    $mail = new PHPMailer();dump($mail);exit;
    // send via SMTP
    $mail->IsSMTP ();
    // SMTP 邮件服务器地址，这里需要替换为发送邮件的邮箱所在的邮件服务器地址
    $mail->Host = "smtp.163.com";
    //邮件服务器验证开
    $mail->SMTPAuth = true;
    // SMTP服务器上此邮箱的用户名，有的只需要@前面的部分，有的需要全名。请替换为正确的邮箱用户名
    $mail->Username = "aa@163.com";
    // SMTP服务器上该邮箱的密码，请替换为正确的密码
    $mail->Password = "11111";
    // SMTP服务器上发送此邮件的邮箱，请替换为正确的邮箱  ,与$mail->Username 的值是对应的。
    $mail->From = "aa@163.com";
    // 真实发件人的姓名等信息，这里根据需要填写
    $mail->FromName = "[".date('Y-m-d H:i:s',time ())."]系统邮件";
    // 这里指定字符集！
    $mail->CharSet = "utf-8";
    $mail->Encoding = base64;
    // 收件人邮箱和姓名
    $mail->AddAddress ($to_email, $to_name);
    // 发送 HTML邮件
    $mail->IsHTML (true);
    // 邮件主题
    $mail->Subject = $subject;
    // 邮件内容
    $mail->Body = $body;
    $mail->AltBody = "text/html";
    if (! $mail->Send()) {
        return 0;
    } else {
        return 1;
    }


}
/**
+----------------------------------------------------------
 * 产生随机字串，可用来自动生成密码 默认长度6位 字母和数字混合
+----------------------------------------------------------
 * @param string $len 长度
 * @param string $type 字串类型
 * 0 字母 1 数字 其它 混合
 * @param string $addChars 额外字符
+----------------------------------------------------------
 * @return string
+----------------------------------------------------------
 */
function rand_string($len=6,$type=5,$addChars='') {
    $str ='';
    switch($type) {
        case 0:
            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        case 1:
            $chars= str_repeat('0123456789',3);
            break;
        case 2:
            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars;
            break;
        case 3:
            $chars='abcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        case 4:
            $chars = "们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培着河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借".$addChars;
            break;
        default :
            // 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
            $chars='ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
            break;
    }
    if($len>10 ) {//位数过长重复字符串一定次数
        $chars= $type==1? str_repeat($chars,$len) : str_repeat($chars,5);
    }
    if($type!=4) {
        $chars   =   str_shuffle($chars);
        $str     =   substr($chars,0,$len);
    }else{
        // 中文随机字
        for($i=0;$i<$len;$i++){
            $str.= msubstr($chars, floor(mt_rand(0,mb_strlen($chars,'utf-8')-1)),1);
        }
    }
    return $str;
}
/**
 * 通用导出EXCEL表格函数
 *@param $data    三维数组 统计数据
 *@param $title   一维数组或字符串   表格标题 (如是字符串则表示固定的表头如:CardBalanceQuery)
 *@param $width   每列的宽度 默认为20
 *@param $filename 下载的文件名
 *@示例：
$data['list'][] = array('brand_name' => '上海大众','amount' => '1,252,717.00','integral' => '3,404','subtotal' => '1,252,717.00','counts' => 114,'status' => '正常');
$data['list'][] = array('brand_name' => '上海大众','amount' => '1,252,717.00','integral' => '3,404','subtotal' => '1,252,717.00','counts' => 114,'status' => '正常');
$data['total'][] = array('总额'=>10234400);
$data['total'][] = array('总单数'=>10534250);
$data['total'][] = array('总积分'=>345523);
$title = array('品牌','消费金额(元)','消费积分','小计','单数','结算状态');
 */
function common_export_excel($data=array(),$title=array(),$width=array(),$filename='report')
{

    Vendor('EXCEL.PHPExcel');
    //设置标题
    $objPHPExcel = new PHPExcel();
    //设置所有单元格默认为左对齐
    $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

    //统计表最多支持36列
    $columns = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ');
    //默认列宽度
    $default_width = 20;
    /*
    示例数据:
    $title = array('品牌','消费金额(元)','消费积分','小计','单数','结算状态');
     */
    //设置表格标题
    if(!empty($title) && is_array($title)){
        $start_column = 0;//循环开始列的下标
        foreach($title as $value){
            if(!empty($width[$start_column])){
                //设置列宽
                $objPHPExcel->getActiveSheet(0)->getColumnDimension($columns[$start_column])->setWidth($width[$start_column]);
            }else{
                //设置默认列宽
                $objPHPExcel->getActiveSheet(0)->getColumnDimension($columns[$start_column])->setWidth($default_width);
            }

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$start_column].'1', $value); //设置表格标题单元格的值
            $start_column++;
        }

        $line = 2;//数据从第二行开始

    }

    /*
    示例数据:
    $data['list'][] = array('brand_name' => '上海大众','amount' => '1,252,717.00','integral' => '3,404','subtotal' => '1,252,717.00','counts' => 114,'status' => '正常');
    $data['list'][] = array('brand_name' => '上海大众','amount' => '1,252,717.00','integral' => '3,404','subtotal' => '1,252,717.00','counts' => 114,'status' => '正常');
    */

    //设置每行的值
    if(!empty($data['list'])){

        foreach($data['list'] as $item){

            if(!empty($item)){
                $start_column = 0;//循环开始列的下标
                foreach($item as $value){
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValueExplicit($columns[$start_column].$line, $value,PHPExcel_Cell_DataType::TYPE_STRING);
                    $start_column++;
                }
                $line++;
            }
        }

    }

    //设置总额信息
    /*
    示例数据:
    $data['total'][] = array('总额'=>10234400);
    $data['total'][] = array('总单数'=>10534250);
    $data['total'][] = array('总积分'=>345523);
    */
    if(!empty($data['total'])){
        $start_column = 0;//循环开始列的下标
        foreach($data['total'] as $value){

            if(!empty($value)){
                foreach($value as $k => $v){

                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$start_column].($line), $k);
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$start_column+1].($line), $v);
                }

                $start_column = $start_column + 2;
            }
        }
    }

    //设置表标题
    $objPHPExcel->getActiveSheet()->setTitle($filename);

    $filename = iconv("utf-8", "gb2312", $filename);

    $objPHPExcel->setActiveSheetIndex(0);
    ob_end_clean();
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
    header('Cache-Control: max-age=0');

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}
function _access($allowDomain=false)
    {
        $allow_origin = array( 'abc.com');
        $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
        if(in_array($origin, $allow_origin)){
            header('Access-Control-Allow-Origin:'.$origin);
			if($allowDomain){//允许携带cookie
				header('Access-Control-Allow-Credentials:true');
			}
            header('Access-Control-Allow-Methods:POST,GET,INPUT');
            header('Access-Control-Allow-Headers:x-requested-with,content-type');
        }
        /*  header('Access-Control-Allow-Origin: '.C('THIRDPART_URL').','.C('SHOW_URL').','.C('ECAR_URL'));
          header("Access-Control-Allow-Methods: GET, POST, PUT");*/
    }
	/**
 * 格式化的打印
 * @param array $arr
 * @return array
 */
function print_g($arr=array(),$is_exit=true)
{
    echo '<pre>';
    print_r($arr);
    echo '</pre>';
    if($is_exit){
        exit;
    }
}